package cn.usian.cart.service.impl;

import cn.usian.cart.mapper.CartMapper;
import cn.usian.cart.service.CartService;
import cn.usian.comon.iterceptor.AutoThreadLocal;
import cn.usian.feign.ProductFeign;
import cn.usian.jyzx.model.entity.h5.CartInfo;
import cn.usian.jyzx.model.entity.product.ProductSku;
import cn.usian.jyzx.model.entity.user.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    CartMapper cartMapper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    ProductFeign productFeign;
    @Override
    public void addToCart(Integer skuId, Integer skuNum) {

        /*
         * 思路：
         *     将该购物项添加到购物车
         *     添加到redis中
         *     大key 是 jyzx_cart
         *     小key 是 购物项的id  skuId
         *     value 是 该购物项
         *  问题：
         *       通过skuId查询对应的购物项？ 通过商品查询，购物车服务远程调用
         *       大key能叫jyzx_cart？ 不能 应该加用户id
         * */
        //1.获取用户Id
//        Long userid = getUserid(token);
        Long userid = AutoThreadLocal.getThreadLocal().getId();

        String cartinfojson = (String) redisTemplate.opsForHash().get("jyzx" + userid, skuId + "");
//        判断该购物车是否有该商品
        if (cartinfojson!=null && cartinfojson !=""){
            CartInfo cartInfo = JSON.parseObject(cartinfojson, CartInfo.class);
//            有的话数量加1
            cartInfo.setSkuNum(cartInfo.getSkuNum()+1);
//            更新到redis
            redisTemplate.opsForHash().put("jyzx"+userid,skuId+"",JSON.toJSONString(cartInfo));
            return;
        }

        CartInfo cartInfo = new CartInfo();
        ProductSku productSku = productFeign.getBySkuId(skuId);
        cartInfo.setCartPrice(productSku.getSalePrice());
        cartInfo.setImgUrl(productSku.getThumbImg());
        cartInfo.setSkuNum(skuNum);
        cartInfo.setIsChecked(1);
        cartInfo.setSkuName(productSku.getSkuName());
        cartInfo.setUserId(userid);
        cartInfo.setSkuId(productSku.getId());
        cartInfo.setUpdateTime(new Date());
        cartInfo.setUpdateTime(new Date());
        redisTemplate.opsForHash().put("jyzx"+userid,skuId+"",JSON.toJSONString(cartInfo));
    }

    @Override
    public List<CartInfo> carList() {
//        Long userid = getUserid(token);
        Long userid = AutoThreadLocal.getThreadLocal().getId();
//        根据大key查询集合
        List<Object> values = redisTemplate.opsForHash().values("jyzx" + userid);
        List<CartInfo> cartInfoList = values.stream().map(CartInfo -> JSON.parseObject(CartInfo.toString(), CartInfo.class)).collect(Collectors.toList());

        return cartInfoList;
    }

    @Override
    public void deleteCart(Integer skuId) {
//        Long userid = getUserid(token);
        Long userid = AutoThreadLocal.getThreadLocal().getId();
        redisTemplate.opsForHash().delete("jyzx"+userid,skuId+"");
    }



    @Override
    public void checkCart(Integer skuId, Integer isChecked) {
//        Long userid = getUserid(token);
        Long userid = AutoThreadLocal.getThreadLocal().getId();
//        获取到商品的购物项
        Object o = redisTemplate.opsForHash().get("jyzx" + userid, skuId + "");
        CartInfo cartInfo = JSON.parseObject(o.toString(), CartInfo.class);
//        重新设置状态
        cartInfo.setIsChecked(isChecked);
//        再次添加到redis
        redisTemplate.opsForHash().put("jyzx"+userid,skuId+"",JSON.toJSONString(cartInfo));
    }

    @Override
    public void allCheckCart(Integer isChecked) {
        Long userid = AutoThreadLocal.getThreadLocal().getId();
//        获取登陆人id
//        Long userid = getUserid(token);
//        获取当前登陆人购物车中的所有商品信息
        List<Object> values = redisTemplate.opsForHash().values("jyzx" + userid);
        values.stream().map(CartInfojson -> JSON.parseObject(CartInfojson.toString(), CartInfo.class))
                .forEach(cartInfo -> {
                    cartInfo.setIsChecked(isChecked);
                    redisTemplate.opsForHash().put("jyzx"+userid,cartInfo.getSkuId()+"",JSON.toJSONString(cartInfo));
                });
    }

    @Override
    public void clearCart() {
//        Long userid = getUserid(token);
        Long userid = AutoThreadLocal.getThreadLocal().getId();
//        删除当前登陆人购物车中的所有信息
        redisTemplate.delete("jyzx"+userid);

    }


    public Long getUserid(String token) {
        String userinfojson = redisTemplate.opsForValue().get(token);
        UserInfo userInfo = JSON.parseObject(userinfojson, UserInfo.class);
        Long userid = userInfo.getId();
        return userid;
    }
}
